"""
FIVEDASH(TM) -- General Purpose Accounting Software
Copyright (C) 2008  Obol Software Pty Ltd

This program is free software: you can redistribute it and/or modify
it. For terms and conditions, see fivedash/license/license.txt

"""

import action
import phunc.utils as utils
from phunc.logger import logger

#generic sql action function 
class ActionNotExistError( Exception ):
	pass

def exec_action(cursor, cmd,  paramlist = [], nullify = False , conn = None, escaped = False):
	result = None
	paramlists=[]
	if not action.action_map.has_key( cmd ):
		raise ActionNotExistError,'ActionNotExistError %s' % cmd
	sql = action.action_map[cmd]
	for param in paramlist:
		if not escaped:
			if type(param)==tuple:
				ps=[]
				for tp in list(param):
					tp.replace('"', '\\"').replace("'", "\\'")
					ps.append(tp)
				param=tuple(ps)
			elif type(param)==str:
				#if param.find('=')<0 and param.find(',')<0 and param.find('(')<0 and not escaped:
				param=param.replace('"', '\\"').replace("'", "\\'")
		paramlists.append(param)
	if len(paramlists) != 0:
		sql = sql % tuple( paramlists )
	if nullify:
		sql = utils.nullify(sql)
	logger.debug("***************sql**************")
	logger.debug(sql)
	import time
	import fpformat
	starttime = time.time()
	try:
		cursor.execute( sql )
	except:
		#TODO:conn not a parameter
		raise
		#conn.rollback()
	else:
		result = cursor.rowcount
		usedtime = time.time() - starttime
		logger.debug("*******************execute used*********************")
		logger.debug('%s execute used %ss ' % (cmd,fpformat.fix(usedtime,5)) )
		if sql.strip().lower()[:6] == 'select':
			result = utils.dictfetch( cursor )
		return result
